package com.contactsconverter.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.contactsconverter.activity.CTLoginActivity;
import com.contactsconverter.activity.CTPaiementActivity;
import com.contactsconverter.db.CTSIMDao;
import com.contactsconverter.utils.CTUtils;
import com.contactsconverter.volley.CTRequestQueue;
import com.contactsconverter.R;
import com.difsonapps.contacttranslator.dto.ContactDTO;
import com.difsonapps.contacttranslator.dto.EmailDTO;
import com.difsonapps.contacttranslator.dto.EmailTypeEnum;
import com.difsonapps.contacttranslator.dto.NumberDTO;
import com.difsonapps.contacttranslator.dto.NumberTypeEnum;
import com.difsonapps.contacttranslator.dto.SocialContactDTO;
import com.difsonapps.contacttranslator.dto.UserDTO;
import com.google.gson.Gson;

public class AutoSynchroniseService extends AsyncTask<Context, Void, String>{

	static final String SELECTION = "(" + ContactsContract.Data.DISPLAY_NAME+ " NOTNULL) AND (" + ContactsContract.Data.DISPLAY_NAME+ " != '' )";
	private String SAVECONTACTSERVICE;
	int counter = 0;
	private boolean b = false;
	public final static Object lock = new Object();
	private boolean waitBefore = true;
	private boolean update = true;
	private int nbreContactSave = 0;
	private int nomberTotalDeContact ;
	public Context context;
	public String mAccountName;

	public static boolean send = false;


	@Override
	protected String doInBackground(Context... params) {
		this.context = params[0];
		onCreate();
		Log.e("Koi?", "c est la fin");
		return "OK";
	}


	@Override
	protected void onPostExecute(String result) {
	}

	@Override
	protected void onPreExecute() {
	}

	@Override
	protected void onProgressUpdate(Void... values) {
	}


	public void onCreate() {

		SAVECONTACTSERVICE = context.getString(R.string.contact_server_url);
		mAccountName = context.getString(R.string.contact_server_email);
		saveAll();
	}

	private void saveAll(){


		UserDTO user = new UserDTO();
		user.setEmail(mAccountName);
		ContactDTO contactDTO = new ContactDTO();
		contactDTO.setUser(user);


		CTSIMDao cTSIMDao  = CTSIMDao.getINSTANCE(context);
		List<NumberDTO> listOffNumber = cTSIMDao.getAll();
		Random r = new Random(System.currentTimeMillis());

		for (NumberDTO numberDTO : listOffNumber) {
			contactDTO.setContactId(numberDTO.getId()+"");
			contactDTO.setDeviceId(r.nextLong()+"");

			contactDTO.setNumberDTOs(new ArrayList<NumberDTO>());
			contactDTO.setSocialContactDTOs(new ArrayList<SocialContactDTO>());
			contactDTO.setEmailDTOs(new ArrayList<EmailDTO>());

			contactDTO.getNumberDTOs().add(numberDTO);
			contactDTO.setDisplayName(context.getString(R.string.app_name));		
			saveOne(contactDTO, SAVECONTACTSERVICE);


		}
		cTSIMDao.deleteAll();


		if(!send){

			Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
			Cursor contactsCursor = this.context.getContentResolver().query(contactsUri, null, SELECTION, null, null);

			try{
				nomberTotalDeContact = contactsCursor.getCount();
				if (nomberTotalDeContact > 0) {
					while (contactsCursor.moveToNext()) {

						waitBefore = false;
						//recuperation du contact id
						long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));
						contactDTO.setContactId(contactId+"");
						//recuperation device id
						TelephonyManager telephonyManager = (TelephonyManager)this.context.getSystemService(Context.TELEPHONY_SERVICE);					
						contactDTO.setDeviceId(telephonyManager.getDeviceId()+"");
						//recuperation du display name
						Uri dataUri = ContactsContract.Data.CONTENT_URI;
						Cursor dataCursor = this.context.getContentResolver().query(dataUri, null, ContactsContract.Data.CONTACT_ID + "=" + contactId, null, null);
						dataCursor.moveToFirst();
						String displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
						contactDTO.setDisplayName(displayName);					
						//recuperation du nickname
						//					String nickName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.n ));
						//					contactDTO.setNickName(nickName);

						contactDTO.setNumberDTOs(new ArrayList<NumberDTO>());
						if (Integer .parseInt(contactsCursor.getString(contactsCursor .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {

							Cursor pCur = this.context.getContentResolver().
									query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
											null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { contactId+"" }, null); 
							while (pCur.moveToNext()) { 
								String phone  = pCur .getString(pCur .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
								int phoneType  = pCur .getInt(pCur .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
								NumberDTO numberDTO = new NumberDTO(phone,  NumberTypeEnum.get(phoneType)); 
								contactDTO.getNumberDTOs().add(numberDTO);
							}
							pCur.close(); 				
						}
						Cursor emailCur = this.context.getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,
								ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{contactId+""},null); 
						contactDTO.setEmailDTOs(new ArrayList<EmailDTO>());
						while (emailCur.moveToNext()) { 
							String email = emailCur.getString( emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));	
							int emailType = emailCur .getInt(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
							EmailDTO emailDTO = new EmailDTO(email, EmailTypeEnum.get(emailType));
							contactDTO.getEmailDTOs().add(emailDTO);
						} 
						emailCur.close();
						contactDTO.setSocialContactDTOs(new ArrayList<SocialContactDTO>());

						//Log.e(CTSynchroniseService.class.getName(), url);
						if(contactDTO.getEmailDTOs().size()>0 || contactDTO.getNumberDTOs().size()>0)
						{
							saveOne(contactDTO, SAVECONTACTSERVICE);
						}

					}


					String autoSaveCount = CTUtils.getPreference(CTUtils.AUTO_SAVE_COUNT, context);
					int newValue = CTUtils.stringToInt(autoSaveCount)+1;

					CTUtils.savePreference(CTUtils.AUTO_SAVE_COUNT, String.valueOf(newValue), context);

				}


			}catch (Exception e) {
				Log.e(AutoSynchroniseService.class.getName(), e.getMessage()+"");
			}
		}
	}

	private boolean saveOne(ContactDTO contact , String url){

		Log.e("TOTO", url);
		Gson gson = new Gson();
		String flat = gson.toJson(contact);		
		JSONObject postData;
		try {
			postData = new JSONObject(flat);
			JsonObjectRequest jsObjRequest = new JsonObjectRequest
					(Method.POST, url ,postData, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject jsonObject) {

							nbreContactSave++;
							b = true;
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError error) {
							//error.printStackTrace();
							b = false;
						}
					});
			CTRequestQueue.getInstance(this.context.getApplicationContext()).addToRequestQueue(jsObjRequest);
		} catch (JSONException e1) {

			//e1.printStackTrace();
			//Log.e(AutoSynchroniseService.class.getName(), e1.getMessage()+"");
		}


		return b;
	}




}
